<template>
  <div id="login-content">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      class="nav-bar"
    />
    <!--登录-->
    <van-form  :show-error-message="false" :show-error="false" @submit="login"  @failed="onFailed" validate-first ref="loginForm">
        <van-field
          v-model="user.mobile"
          icon-prefix="toutiao" left-icon="shouji"
          placeholder="请输入手机号"
          :rules="formRule.mobile"
          name="mobile"
        />
        <van-field
          v-model="user.code"
          clearable
          icon-prefix="toutiao" left-icon="yanzhengma"
          placeholder="请输入验证码" class="code"
          :rules="formRule.code"
          name="code"
          >
          <template #button>
            <van-count-down :time="time" format="ss s" v-if="isCountDownTime" @finish="isCountDownTime=false"/>
            <van-button size="small" type="primary" class="send-btn" @click.prevent="onSend" v-else :loding="isSendLoading">发送验证码</van-button>
          </template>
        </van-field>
      <div class="login-btn">
        <van-button type="info" block >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {login,sendSms} from '@/api/user'
export default {
  name: 'login',
  components: {},
  directives: {},
  data(){
    return {
      user:{
        mobile: '13611111111', // 手机号
        code: '246810' // 验证码
      },
      time:1000*60,
      formRule:{
        mobile:[
          { required: true, message: '请填写手机号'},
          {pattern: /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,message: '手机号格式不正确' }
      ],
        code:[
          { required: true, message: '请填写验证码' },
          {pattern: /^\d{6}$/,message: '验证码填写有误' }
      ]
      },
      isCountDownTime:false,
      isSendLoading:false //发送验证码的loading状态
    }
  },
  methods:{
    async login(){
      //1.找到数据接口
      //2.封装请求方法
      //3.请求调用登录
      //4.处理响应结果
      this.$toast.loading({
        message: '登陆中...',
        forbidClick: true,
      });
      try {
        const {data}=await login(this.user);
        this.$toast.success('登录成功~')
        //console.log(res)
        //将后端返回的用户登录的状态（token等数据）放到vuex容器中
        this.$store.commit('setUser',data.data)
        //清除layout的缓存，让它重新渲染
        this.$store.commit('removeCachePage','layout')
        //登录成功
        //this.$router.push(this.$router.query.redirect || '/')
        this.$router.back() //这里暂时使用这种方式
      } catch (error) {
        //console.log('登录失败'+error)
        this.$toast.fail('登录失败~\n请检查手机号和密码');
      }
    },
    onFailed(errorInfo){
       //console.log(errorInfo)
       if(errorInfo.errors[0]){
        this.$toast({
          message:errorInfo.errors[0].message,
          position: 'top',
          forbidClick: true
        })
       }
    },
    //发送验证码
    async onSend(){
      try {
        //验证手机号
        await this.$refs.loginForm.validate('mobile')
        //验证通过
        await sendSms(this.user.mobile)
        //短信发出去了，请求发送验证码
        this.isSendLoading=true
        this.isCountDownTime=true

      } catch (error) {
          //无论成功失败关闭按钮的loading状态
          this.isSendLoading=false
        let message="";
        if(error && error.response && error.response.status === 429){
          //发送太频繁
          message="发送太频繁,请稍后重试"
        }else if(error.name==="mobile"){
          //表单验证失败的错误提示
          message=error.message
        }else {
          //未知错误
          message='发送失败，稍后重试'
          console.log(error)
        }

        //提示
        this.$toast({
          message:message,
          position: 'top',
          forbidClick: true
        })

      }
    }
  }
};
</script>

<style lang="less" scoped>
.login-btn{
  padding:16px 26px;
    .van-button--info{
      background: #6db4fb;
      border:none;
      border-radius: 10px;
  }
  .van-button__text{
    font-size: 20px;
  }
}
.send-btn{
  // width:80px;
  height:23px;
  background: #ededed;
  border-radius: 10px;
  color:#000;
  border:none;
  vertical-align: top;
}
/deep/ .toutiao-yanzhengma{
    align-self: center;
   display: inline-block;
}
/deep/ .toutiao-shouji{
   align-self: center;
   display: inline-block;
}
/deep/ .van-field__control{
  line-height: 30px;
}
</style>
